import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'

import App from './App.vue'
import router from './router'
import { useUserStore } from './stores/user'

// 样式文件
import './styles/index.scss'

const app = createApp(App)

// 注册Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 使用插件
app.use(createPinia())
app.use(router)
app.use(ElementPlus, {
  locale: zhCn,
})

// 全局错误处理
app.config.errorHandler = (err, instance, info) => {
  console.error('Global error:', err)
  console.error('Component instance:', instance)
  console.error('Error info:', info)
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 白名单路由
  const whiteList = ['/login', '/register', '/404']
  
  if (whiteList.includes(to.path)) {
    next()
    return
  }
  
  // 检查用户是否已登录
  if (!userStore.token) {
    next('/login')
    return
  }
  
  // 检查用户信息是否已获取
  if (!userStore.userInfo.id) {
    try {
      await userStore.getUserInfo()
      next()
    } catch (error) {
      console.error('获取用户信息失败:', error)
      userStore.logout()
      next('/login')
    }
  } else {
    next()
  }
})

app.mount('#app')
